package com.sky.controller.common;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/admin/common")
@Api("通用接口")
@Slf4j
public class commonCtroller {

    @Autowired
    AliOssUtil ossUtil;
    //文件上传接口
    @PostMapping("/upload")
    @ApiOperation("上传接口")
    public Result upload(MultipartFile file){
        log.info("上传文件{}",file);

        try {
            //防止重名 我们使用uuid来编写名字
            //1.获取原始名
            String originalFilename = file.getOriginalFilename();
            //2.获取后缀 拼接uuid
            int index = originalFilename.lastIndexOf("."); //获取拓展名最后一个点的位置
            String expandName = originalFilename.substring(index);
            String objectName = UUID.randomUUID().toString()+expandName;
            //返回文件的请求路径
            String filePath = ossUtil.upload(file.getBytes(), objectName);
            log.info("返回的文件路径{}",filePath);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败{}",e);
        }
            return null;
    }
}
